package net.kaaass.tools.gradequery;

import javafx.util.Pair;
import net.kaaass.tools.gradequery.network.CrazyGet;
import net.kaaass.tools.gradequery.network.Query;
import net.kaaass.tools.gradequery.util.FileUtil;
import net.kaaass.tools.gradequery.util.StringUtil;
import org.apache.poi.ss.util.CellRangeAddress;

import javax.swing.*;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class MainForm {
    private JTextField tfInput;
    private JTextField tfDataZoom;
    private JTextField tfExamIdCol;
    private JTextField tfIdCol;
    private JTextField tfOutput;
    private JButton btnLoad;
    private JButton btnSave;
    private JProgressBar pbProgress;
    private JButton btnStart;
    private JButton btnClose;
    private JPanel Main;
    private JLabel lbStatus;
    private JTextField tfTbl;
    private JButton btnCrazy;
    private File fInput;
    public static File fOutput = new File("result.xls");
    private static boolean isRun = false;

    public MainForm() {
        /*
        载入
         */
        btnLoad.addActionListener(e -> {
            JFileChooser fileChooser = new JFileChooser();
            fileChooser.setDialogTitle("请选择学生数据");
            // fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
            fileChooser.setFileFilter(new FileFilter() {
                @Override
                public boolean accept(File f) {
                    return f != null && (f.getName().endsWith(".xls"));
                }

                @Override
                public String getDescription() {
                    return "Excel表格(*.xls)";
                }
            });
            fileChooser.showOpenDialog(null);
            if (fileChooser.getSelectedFile() != null) {
                this.fInput = fileChooser.getSelectedFile();
                tfInput.setText(this.fInput.getAbsolutePath());
            }
        });
        /*
        保存
         */
        btnSave.addActionListener(e -> {
            FileNameExtensionFilter filter = new FileNameExtensionFilter("Excel表格(*.xls)", "*.xls");
            JFileChooser fileChooser = new JFileChooser();
            fileChooser.setFileFilter(filter);
            fileChooser.setMultiSelectionEnabled(false);
            fileChooser.setDialogTitle("请选择保存位置");
            fileChooser.setFileSelectionMode(JFileChooser.SAVE_DIALOG);
            int result = fileChooser.showSaveDialog(null);
            if (result == JFileChooser.APPROVE_OPTION) {
                this.fOutput = fileChooser.getSelectedFile();
                if (!this.fOutput.getPath().endsWith(".txt"))
                    this.fOutput = new File(this.fOutput.getPath() + ".txt");
                tfOutput.setText(this.fOutput.getAbsolutePath());
            }
        });
        /*
        退出
         */
        btnClose.addActionListener(e -> {
            System.exit(0);
        });
        btnStart.addActionListener(e -> {
            if (isRun) {
                JOptionPane.showMessageDialog(null, "程序已经在查询！", "提示", JOptionPane.WARNING_MESSAGE);
                return;
            }
            isRun = true;
            startQuery();
        });
        btnCrazy.addActionListener(e -> {
            JOptionPane.showMessageDialog(null, "欢迎使用强制查找！提示：查找不出程序不响应，结果保存在软件目录下“疯狂查询结果.html”", "提示", JOptionPane.INFORMATION_MESSAGE);
            String id = JOptionPane.showInputDialog(null,"请输入身份证号",JOptionPane.QUESTION_MESSAGE);
            String eid = JOptionPane.showInputDialog(null,"请输入准考证号",JOptionPane.QUESTION_MESSAGE);
            JOptionPane.showMessageDialog(null, "点击后开始查询", "提示", JOptionPane.INFORMATION_MESSAGE);
            try {
                CrazyGet.get(id, eid);
            } catch (IOException e1) {
                e1.printStackTrace();
                JOptionPane.showMessageDialog(null, "查询失败", "提示", JOptionPane.INFORMATION_MESSAGE);
            }
            JOptionPane.showMessageDialog(null, "查询成功！结果保存在软件目录下“疯狂查询结果.html”", "提示", JOptionPane.INFORMATION_MESSAGE);
        });
    }

    public static void main(String[] args) {
        try {
            UIManager.setLookAndFeel(new com.sun.java.swing.plaf.windows.WindowsLookAndFeel());
        } catch (UnsupportedLookAndFeelException e) {
            e.printStackTrace();
        }
        JFrame frame = new JFrame("学考成绩批量查询（201704版）");
        frame.setContentPane(new MainForm().Main);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setBounds(0, 0, 500, 430);
        frame.setLocationRelativeTo(null);
        frame.pack();
        frame.setVisible(true);
    }

    public static void updateProg(MainForm mf, int progress) {
        mf.pbProgress.setValue(progress);
    }

    public static void updateTip(MainForm mf, String tips) {
        mf.lbStatus.setText(tips);
    }

    private void startQuery() {
        new Thread(() -> {
            List<Pair<String, String>> data = new ArrayList<>();
            ThreadPool threadPool;
            try {
                /*
                解析xls 获取数据
                */
                updateTip(this, "开始解析表格");
                int st = 0;
                int ed = 0;
                CellRangeAddress cellRangeAddress = CellRangeAddress.valueOf(tfDataZoom.getText());
                st = cellRangeAddress.getFirstRow();
                ed = cellRangeAddress.getLastRow();
                data = FileUtil.readIn(fInput,
                        tfTbl.getText(),
                        StringUtil.colToShort(tfIdCol.getText()),
                        StringUtil.colToShort(tfExamIdCol.getText()),
                        st, ed
                );
                /*
                请求
                 */
                updateTip(this, "正在查询");
                threadPool = ThreadPool.init();
                threadPool.loadIn(data);
                threadPool.start(this);
            } catch (Exception e) {
                e.printStackTrace();
                JOptionPane.showMessageDialog(null, "程序运行时遇到错误：" + e.getLocalizedMessage(), "错误", JOptionPane.ERROR_MESSAGE);
                end(this);
            }
        }).start();
    }

    public static void end(MainForm mf) {
        updateTip(mf, "完毕");
        isRun = false;
    }
}
